<?php
declare (strict_types = 1);

namespace app\month\controller;

use app\month\business\UserBusiness;
use think\Exception;

class User
{

    /**
     * 接口安全：token(维持用户的登录状态 JWT是个什么东西、怎么用？)、时间戳机制、签名机制
     * 跨域问题、如何解决？
     * 接口版本
     * 统一的响应方法
     */

    /**
     * 注册/登录接口
     * code 小程序临时标识、只能使用一次
     */
    public function getOpenid(){
        try {

//            代码体
            $code = request()->post('code');
            if (empty($code)) {
                throw new Exception("code参数不能为空",2001);
            }

            $third_config = config('third');// 获取配置文件里面的信息
            $third_config['mini']['js_code']= $code;// 替换前端传送的参数
            $url =  $third_config['mini']['openid_url'];
            unset($third_config['mini']['openid_url']);

            $param = http_build_query($third_config['mini']);

            $url = $url . "?".$param;

            $result = file_get_contents($url);
            $result = json_decode($result,true);
            // 为了调试

            if (isset($result['errcode'])) {
                throw  new Exception("第三方服务异常、请稍后重试",2101);//手动抛出异常
            }

            # 判断用户是否注册
            $token = UserBusiness::login($result['openid']);

            return success(['token' => $token]);

        }catch (\Exception $exception) {
            return fail($exception->getCode(),$exception->getMessage());
        }
    }

    /**
     * 更新昵称、头像接口
     * @return \think\response\Json
     */
    public function updateAuthMessage(): \think\response\Json
    {
        try {

//            代码体

            $nickname = request()->post('nickname');
            $avatar = request()->post('avatar');

            if (empty($nickname) || empty($avatar)) {
                throw  new Exception("参数错误",2001);

            }

            $uid = request()->uid;

            \app\month\model\User::update([
                'nickname' => $nickname,
                'avatar' => $avatar,
                'id' => $uid
            ]);

            return success([]);

        }catch (\Exception $exception) {
            return fail($exception->getCode(),$exception->getMessage());
        }
    }

    /**
     * 更新地址位置接口
     * @return \think\response\Json
     */
    public function updateLocationMessage(): \think\response\Json
    {
        try {

//            代码体
            $city = request()->post('city');
            $lat = request()->post('lat');
            $log = request()->post('log');

            if (empty($city) || empty($lat) ||empty($log)) {
                throw  new Exception("参数错误",2001);

            }

            $uid = request()->uid;

            \app\month\model\User::update([
                'city' => $city,
                'lat' => $lat,
                'log' => $log,
                'id' => $uid
            ]);

            return success([]);

        }catch (\Exception $exception) {
            return fail($exception->getCode(),$exception->getMessage());
        }
    }


}
